from flask import Blueprint, jsonify, request
from ..models.oil_tank import OilTank
from .. import db

bp = Blueprint('oil_tanks', __name__, url_prefix='/api/oil-tanks')

@bp.route('', methods=['GET'])
def get_oil_tanks():
    oil_tanks = OilTank.query.all()
    return jsonify([tank.to_dict() for tank in oil_tanks])

@bp.route('/<int:id>', methods=['GET'])
def get_oil_tank(id):
    oil_tank = OilTank.query.get_or_404(id)
    return jsonify(oil_tank.to_dict())

@bp.route('', methods=['POST'])
def create_oil_tank():
    data = request.get_json()
    oil_tank = OilTank(
        airport_id=data['airport_id'],
        name=data['name'],
        type=data['type'],
        area=data['area']
    )
    db.session.add(oil_tank)
    db.session.commit()
    return jsonify(oil_tank.to_dict()), 201

@bp.route('/<int:id>', methods=['PUT'])
def update_oil_tank(id):
    oil_tank = OilTank.query.get_or_404(id)
    data = request.get_json()
    
    oil_tank.airport_id = data.get('airport_id', oil_tank.airport_id)
    oil_tank.name = data.get('name', oil_tank.name)
    oil_tank.type = data.get('type', oil_tank.type)
    oil_tank.area = data.get('area', oil_tank.area)
    
    db.session.commit()
    return jsonify(oil_tank.to_dict())

@bp.route('/<int:id>', methods=['DELETE'])
def delete_oil_tank(id):
    oil_tank = OilTank.query.get_or_404(id)
    db.session.delete(oil_tank)
    db.session.commit()
    return '', 204 